package com.wb.spring.boot.autoconfigure.http;

import com.wb.spring.boot.autoconfigure.annotation.ConditionalOnWbClientEnabled;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;


/**
 * @Author deeprado
 * @Date 2022/8/25 19:25
 */
@Slf4j
@ConditionalOnWbClientEnabled
@ConditionalOnOkHttpEnabled
@ConditionalOnHttpTypeOkHttp
@Configuration
@AutoConfigureAfter({WbClientAutoConfiguration.class, WbClientAutoConfiguration.class})
public class WbOkHttpAutoConfiguration {

    @Autowired
    public OKHttpProperties okHttpProperties;

    /**
     * 声明 RestTemplate
     */
    @Bean
    @ConditionalOnMissingBean
    public RestTemplate restTemplate() {
        ClientHttpRequestFactory factory = httpRequestFactory();
        RestTemplate restTemplate = new RestTemplate(factory);
        log.info("基于okhttp的RestTemplate构建完成！ = {}", restTemplate);
        return restTemplate;
    }

    /**
     * 工厂
     *
     * @return
     */
    private ClientHttpRequestFactory httpRequestFactory() {
        return new OkHttp3ClientHttpRequestFactory(okHttpConfigClient());
    }

    /**
     * 客户端
     *
     * @return
     */
    private OkHttpClient okHttpConfigClient() {
        return new OkHttpClient().newBuilder()
                .connectionPool(pool())
                .connectTimeout(okHttpProperties.getConnectTimeout(), okHttpProperties.getConnectTimeoutTimeUnit())
                .readTimeout(okHttpProperties.getReadTimeout(), okHttpProperties.getReadTimeoutTimeUnit())
                .writeTimeout(okHttpProperties.getWriteTimeout(), okHttpProperties.getWriteTimeoutTimeUnit())
                .hostnameVerifier((hostname, session) -> true)
                .build();
    }

    /**
     * 连接池
     *
     * @return
     */
    private ConnectionPool pool() {
        return new ConnectionPool(okHttpProperties.getMaxIdleConnections(), okHttpProperties.getKeepAliveDuration(), okHttpProperties.getKeepAliveDurationTimeUnit());
    }
}
